package com.guyaogg.gulimall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guyaogg.common.utils.PageUtils;
import com.guyaogg.common.utils.Query;
import com.guyaogg.gulimall.order.dao.OrderItemDao;
import com.guyaogg.gulimall.order.entity.OrderEntity;
import com.guyaogg.gulimall.order.entity.OrderItemEntity;
import com.guyaogg.gulimall.order.entity.OrderReturnReasonEntity;
import com.guyaogg.gulimall.order.service.OrderItemService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;


@Slf4j
@Service("orderItemService")
@RabbitListener(queues = {"hello-java-queue"})
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * RabbitListener 声明监听的队列
     *
     * @param message    : 原生消息信息：头 + 体
     * @param content<T> : 任意类型接收，spring 自动转化
     * @param channel    : 传输数据的通道
     *  Queue 可以很多人监听，只能收到消息，队列删除消息，而且只能有一个收到此消息
     *    场景：
     *         订单服务启动多个，竞争收取
     *
     */
//    @RabbitListener(queues = {"hello-java-queue"})
    @RabbitHandler
    public void receiveMessage(Message message, OrderReturnReasonEntity content,
                               Channel channel) throws InterruptedException {
        log.debug("接收消息...内容:{},===>类型：{}", message, message.getClass());
        log.debug("自动转化的对象：{}", content);
        // channel 内自增
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 签收消息,标签，是否批量签收
        try {
            // 收货
            channel.basicAck(deliveryTag,false);
            // 拒货,标签，批量，是否重新入队
            channel.basicNack(deliveryTag,false,true);
//            channel.basicReject();
        } catch (IOException e) {
            // 网络中断
            e.printStackTrace();
        }

    }
    @RabbitHandler
    public void receiveMessage2(Message message, OrderEntity content,
                               Channel channel) throws InterruptedException {
        log.info("消息处理完成==>{},channel:{}",content,channel);

    }

}